from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """添加购物车数据系列化器"""
    sku_id = serializers.IntegerField(label='商品ID', min_value=1)
    count = serializers.IntegerField(label="商品数量", min_value=1)
    selected = serializers.BooleanField(label="是否勾选", default=True)

    def validate(self, data):
        try:
            sku = SKU.objects.get(id=data['sku_id'])
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        if data['count'] > sku.stock:
            raise serializers.ValidationError("商品库存不足")
        return data


class CartSKUSerializer(serializers.ModelSerializer):
    """查询购物车商品数据序列化器"""
    count = serializers.IntegerField(label="数量")
    selected = serializers.BooleanField(label="是否勾选")

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


class CartDelSerializer(serializers.Serializer):
    """购物车记录删除序列化器"""
    sku_id = serializers.IntegerField(label="商标SKU编号")

    def validate_sku_id(self, value):
        """判断商品是否存在"""
        try:
            sku = SKU.objects.get(id=value)
        except Exception:
            raise serializers.ValidationError("商品不存在")

        return value


class CartSelectAllSerializer(serializers.Serializer):
    """购物车全选序列化器类"""
    selected = serializers.BooleanField(label='全选')